import Vue from 'vue'
import {
	request
} from '@/request/index.js'

export const store = Vue.observable({
	osName: '', //用户手机系统  ios android
	skin: ``, //皮肤
	start_page_status: 0, // 热启动只允许用户进入一次启动页 0是未进入过，1是已经进入过
	pageLoadingState: false, //页面loading
	pageLoadingText: '', //页面loading上的提示文字
	pageLoadingBgColor: 'transparent', //页面loading背景颜色
	primaryBgTextColor: 'white', //主题色为背景时对应的文本颜色，目前通过判断主题色来计算为白色或者黑色
	primaryBgColor: '#ffffff', //主题色为背景时需要设置的背景色，设置了才能同时设置标题颜色
	image_header: '', //服务端图片地址前半部分 如https://retail.mobzhifu.com/Public/miniProgram/images/
	statusBarHeight: 0, //状态栏高度
	bottomHeight: 0, //部分机型底部需要留白的高度
	merHomeState: true, //是否开启商户版首页
	mallPreviewState: false, //是否开启商城前置页  【商户版商城优先于商城前置页】
	showStoreTypeState: false, //是否显示门店类型  直营或加盟
	merShoppingGoodsList: [], //商户商品购物车列表
	storeShoppingGoodsList: [], //门店商品购物车数据
	carStoreId: '', //当前存储的门店商品购物车数据对应的门店id
	store_id: '1', //当前请求参数中的门店id
	begin_store_id: '', //切换门店后的门店id
	navigation_status: false, // 是否开启自定义导航栏
	diy_navigation: [], // 自定义导航栏
	tabbarBoxStyle: {}, // 自定义导航栏样式设置

	integral_arrive_cash: 0, //商户是否开启积分抵现
	marketing_methods: 1, //积分抵现模式  1基于订单  2基于商品
	allGoodsList:[],
	merCheckShopCarIds: {}, //商户购物车已选中的id列表，注意：为了简化页面代码，防止初始化时被重置，存储的id在购物车中不一定存在
	storeCheckShopCarIds: {}, //门店购物车已选中的id列表，注意：为了简化页面代码，防止初始化时被重置，存储的id在购物车中不一定存在
	
	checkedList:[],  //购物车勾选状态
	address_id: null,   //地址ID
	merTabbarList: [{
			name: '首页',
			icon: 'qh-rt-a-zu24311',
			page: '/pages/mer/tabbar/home/home',
			current: 0,
		},
		{
			name: '分类',
			icon: 'qh-rt-a-zu24301',
			page: '/pages/mer/tabbar/category/category',
			current: 1,
		},
		{
			name: '门店',
			icon: 'qh-rt-a-zu4313',
			page: '/pages/mer/tabbar/store/store',
			current: 2,
		},
		{
			name: '购物车',
			icon: 'qh-rt-a-zu24291',
			page: '/pages/mer/tabbar/shoppingCar/shoppingCar',
			current: 3,
		},
		{
			name: '我的',
			icon: 'qh-rt-a-zu2427',
			page: '/pages/mer/tabbar/my/my',
			current: 4,
		},
	],
	storeTabbarList: [{
			name: '首页',
			icon: 'qh-rt-a-zu24311',
			page: '/pages/store/store',
			current: 0,
		},
		{
			name: '分类',
			icon: 'qh-rt-a-zu24301',
			page: '/pages/newClassify/newClassify',
			current: 1,
		},
		{
			name: '购物车',
			icon: 'qh-rt-a-zu24291',
			page: '/pages/shoppingCar/shoppingCar',
			current: 2,
		},
		{
			name: '订单',
			icon: 'qh-rt-a-zu24281',
			page: '/pages/myOrder/myOrder',
			current: 3,
		},
		{
			name: '我的',
			icon: 'qh-rt-a-zu2427',
			page: '/pages/my/my',
			current: 4,
		},
	],
	userInfo: {
		access_token: null,
		avatar: "",
		card_num: "",
		external_user_id: "",
		guide_id: "0",
		id: "",
		key: "",
		link_name: "",
		login_state: "0",
		merchant_id: "",
		mobile_phone: "",
		nickname: "",
		openid: "",
		ordinary_openid: null,
		original_type: "1",
		platform_type: "1",
		plus_vip_id: "0",
		service_openid: "",
		session_key: "",
		store_id: "",
		type: "1",
		uid: "",
		unionid: "",
		vid: null,
	}, //登录的用户信息
	info: {
		name: '',
		avatar: '',
		phone: '',
		time: ''
	},
	distributor_id: 0,
	invite: {},
	merCouponInvite: {}, // 分享商家券详情未登录时存的商家券ID和type
	bottomHeight: 0, // 部分机型底部需要留白的高度
	closeDialogList: [], // diy关闭过的弹窗 记录，下次不会自动弹窗
	userPositionInfo: null,
	integral_name:'', //积分自定义名称
})
export const mutations = {
	showLoading(options = '') {
		store.pageLoadingState = true;

		if (typeof options == 'string') {
			store.pageLoadingText = options;
		} else if (typeof options == 'object') {
			store.pageLoadingText = options.title ? options.title : '';
			store.pageLoadingBgColor = options.backgroundColor ? options.backgroundColor : 'transparent';
		} else {
			store.pageLoadingText = '';
		}
	},
	hideLoading() {
		store.pageLoadingState = false;
		store.pageLoadingBgColor = 'transparent';
		store.pageLoadingText = '';
	},
	//获取用户位置和位置名称
	getLocation() {
		return new Promise((resolve) => {
			let positionInfo = store.userPositionInfo;
			if (positionInfo) {
				return resolve(positionInfo);
			}
			uni.getLocation({
				// #ifdef MP-WEIXIN
				type: 'gcj02',
				// #endif
				success: async (res) => {
					const {
						status,
						message,
						data
					} = await request('SmallProgramApi/My/getUserLocation', {
						longitude: res.longitude,
						latitude: res.latitude,
					});
					if (status == 1) {
						let info = {
							longitude: res.longitude,
							latitude: res.latitude,
							name: data,
						}
						store.userPositionInfo = info;
						resolve(info);
					} else {
						// resolve(false);
						// uni.showToast({
						// 	title: message,
						// 	icon: false
						// })
						uni.showModal({
							title: '温馨提示',
							content: message + '，是否手动选择位置？',
							success: (res) => {
								if (res.confirm) {
									uni.chooseLocation({
										success: (res) => {
											store.userPositionInfo = res;
											resolve(res);
										},
										fail: () => {
											resolve(false);
										}
									});
								} else {
									resolve(false);
								}
							}
						})
					}
				},
				fail: (res) => {
					uni.showModal({
						title: '温馨提示',
						content: '您已拒绝授权位置，将不可使用部分功能，是否手动选择位置？',
						success: (res) => {
							if (res.confirm) {
								uni.chooseLocation({
									success: (res) => {
										store.userPositionInfo = res;
										resolve(res);
									},
									fail: () => {
										resolve(false);
									}
								});
							} else {
								resolve(false);
							}
						}
					})
				}
			});
		})
	},
	saveInfo(data) {
		let {
			nickname,
			avatar,
			phone_number,
			add_time,
			uid,
			distributor_id
		} = data;
		store.info['name'] = nickname;
		store.info['avatar'] = avatar;
		store.info['phone'] = phone_number;
		store.info['time'] = add_time;
		store.info['uid'] = uid;
		store.info['distributor_id'] = distributor_id;
	},
	saveDistributor_id(id) {
		store.distributor_id = id;
	},
	// 分销员
	setDistributor(data) {
		let {
			isRecruit,
			distributor_id
		} = data;
		store.invite['isRecruit'] = isRecruit;
		store.invite['distributor_id'] = distributor_id;
	},
	//分享商家券
	getMercouponInvite(data) {
		store.merCouponInvite['id'] = data.id;
		store.merCouponInvite['type'] = data.type;
		store.merCouponInvite['isLogin'] = data.isLogin;
		store.merCouponInvite['genre'] = data.genre;
	},
	//修改皮肤
	skinPeeler(rgb, test_color_type) {
		if (!rgb) {
			rgb = 'rgb(255, 92, 109)'; //默认主题色
			// rgb = 'rgb(131, 205, 67)';
		}
		if (!test_color_type) {
			test_color_type = 2;
		}
		let num = rgb.replace("rgb(", "").replace(")", "");
		store.primaryBgTextColor = test_color_type == 2 ? '#ffffff' : '#000000';
		store.primaryBgColor = test_color_type == 2 ? '#000000' : '#ffffff';
		store.skin = `--primary-color: ${rgb};--primary-rgb-color: ${num};--primary-bg-text-color: ${store.primaryBgTextColor}`;
		getApp().globalData.primarySkinObj = {
			primaryColor: rgb,
			primaryRGBColor: num,
		};
	},
	// 获取商户商品购物车数据
	getShopList(goodsType = 1, store_id = '') {
		return new Promise(async (resolve, reject) => {
			let url = 'Shopping/getShoppingGoods_v4'
			const {
				status,
				data,
				message
			} = await request('SmallProgramApi/' + url , { store_id: store.mallStoreId });
			if (status == 1) {
				let goodsList = data.list.map(item => {
					return {
						id: item.id,
						goods_id: item.goods_id,
						sku_id: item.sku_id,
						num: item.num,
					}
				})
				// 获取购物车商品列表
				if (goodsType == 1) {
					store.merShoppingGoodsList = goodsList;
				} else {
					store.carStoreId = store_id ? store_id : store.store_id;
					store.storeShoppingGoodsList = goodsList;
				}

				resolve(true)
			} else {
				reject(false)
			}
		})
	},
	/**设置购物车商品
	 * @param {Object} param
	 * [
	 * id			购物车id
	 * goods_id		商品id
	 * sku_id		规格id
	 * num			数量
	 * goods_type	1商户  2门店  不传默认商户
	 * ]
	 */
	setShoppingCar(param) {
		return new Promise(async (resolve, reject) => {
			//查找购物车中是否含有此商品
			let list = param.goods_type == 2 ? store.storeShoppingGoodsList : store.merShoppingGoodsList;
			let index = list.findIndex((item) => {
				return param.goods_id == item.goods_id && (!param.id && (!param.sku_id || param.sku_id == item.sku_id) || param.id ==
					item.id);
			})
			if (param.id && index >= 0 && param.num == list[index].num && (!param.sku_id || param.sku_id == list[index].sku_id)) return resolve(
				true);

			// 数量大于0
			param.num = param.num * 1;
		
			if (param.num > 0) {
				let obj = index == -1 ? {
					goods_id: param.goods_id,
					sku_id: param.sku_id,
					num: param.num,
					store_id: store.mallStoreId,
				} : {
					id: list[index].id,
					// num:param.id ? param.num : toDecimal(param.num + list[index].num * 1),
					num: param.num ,
					sku_id: param.sku_id,
					store_id: store.mallStoreId,
				};
				let url;
				if (index == -1) {
					//加入购物车
					url = 'Shopping/addShopping_v1' 
				} else if (param.sku_id && param.sku_id != list[index].sku_id) {
					//修改规格
					url = 'Shopping/changeSelectSku_v1'
				} else {
					//修改数量
					url = 'Shopping/changeCartNum_v1'
				}

				var {
					status,
					message,
					data,
					id,  
				} = await request('SmallProgramApi/' + url, obj)
			} else {
				// 删除购物车数据
				if (index == -1) {
					// uni.showToast({
					// 	title: '操作有误，购物车不存在此商品',
					// 	icon: 'none',
					// })
					reject(false);
					return;
				}
				let url = 'Shopping/deleteShopping_v1'
				var {
					status,
					message,
					data,
				} = await request('SmallProgramApi/' + url, {
					id: JSON.stringify(list[index].id),
					store_id: store.mallStoreId,
				})
			}
			if (status == 1) {
				(!param.id || index == -1) && param.num > 0 
				// && uni.showToast({
				// 	title: '加入购物车成功',
				// 	duration: 1000
				// })
				if (index == -1) {
					//插入数据
					list.push({
						id: id ,
						goods_id: param.goods_id,
						sku_id: param.sku_id,
						num: param.num,
					});
				} else if (param.num > 0) {
					//直接修改数量
					// list[index].num = (!param.id ? (list[index].num * 1) : 0) + param.num;
					list[index].num =  param.num;

				} else {
					//删除
					list.splice(index, 1);
				}
				if (param.goods_type == 2) {
					store.storeShoppingGoodsList = list;
				} else {
					store.merShoppingGoodsList = list;
				}

				resolve(true)
			} else {
				uni.showToast({
					title: message,
					icon: 'none'
				})
				resolve(false)
			}
		})
	},

	
}

